<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="出库单号" prop="cDanhao">
        <el-input
          v-model="queryParams.cDanhao"
          placeholder="请输入出库单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出库仓库" prop="kuId">
        <el-select v-model="queryParams.kuId" placeholder="请选择仓库" style="width: 150px;">
          <el-option
            v-for="item in cangkuList"
            :key="item.kuId"
            :label="item.kuName"
            :value="item.kuId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['jiuzai:chuku:add']"
        >新增</el-button>
      </el-col>

      <el-button
      type="info"
      plain
      icon="View"
      @click="handleBatchView"
      v-hasPermi="['jiuzai:wuziruku:query']"
    >查看</el-button>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jiuzai:chuku:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jiuzai:chuku:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['jiuzai:chuku:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chukuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="出库序号" align="center" prop="cId" />
      <el-table-column label="出库仓库" align="center" prop="kuId">
             <template #default="scope">
          <span v-if="scope.row.kuId ===  scope.row.kuId">
            {{ scope.row.cangku?.kuName}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="出库人" align="center" prop="yId">
        <template #default="scope">
          <span v-if="scope.row.yId === scope.row.yId">
            {{ scope.row.table12.yName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="出库单号" align="center" prop="cDanhao" />
      <el-table-column label="出库日期" align="center" prop="cShijian" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.cShijian, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- 审核状态 -->
      <el-table-column label="领取人" align="center" prop="cLingquren" >
        <template #default="scope">
          <span v-if="scope.row.yId === scope.row.yId">
            {{ scope.row.table12.yName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['jiuzai:chuku:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['jiuzai:chuku:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物资出库对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="chukuRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库" prop="kuId">
          <el-select v-model="form.kuId" placeholder="请选择仓库">
              <el-option
                v-for="item in cangkuList"
                :key="item.kuId"
                :label="item.kuName"
                :value="item.kuId"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="出库人" prop="yId">
          <el-input v-model="form.yId" placeholder="出库人" />
        </el-form-item>
        <el-form-item label="出库单号" prop="cDanhao">
          <el-input v-model="form.cDanhao" placeholder="请输入出库单号" />
        </el-form-item>
        <el-form-item label="出库时间" prop="cShijian">
          <el-date-picker clearable
            v-model="form.cShijian"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="出库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领取人" prop="cLingquren">
          <el-input v-model="form.cLingquren" placeholder="请输入领取人" />
        </el-form-item>
        <el-form-item label="物资详细" prop="rukuXiangqing">
          <el-button 
      type="success" 
      plain 
      icon="Select" 
      @click="handleSelectMingxi"
      v-hasPermi="['jiuzai:wuziruku:add']"
    >选择物资</el-button>
      <!-- 显示已选择的物资明细 -->
      <el-table :data="form.mingxiList || []" border style="margin-top: 10px;">
  <!-- 物资名称(只读) -->
  <!-- 序列号列 -->
 <!-- 物资序号列 -->
 <el-table-column label="物资序号" width="120" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.wuziId" 
        placeholder="请输入物资序号"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>


  <el-table-column label="物资名称" width="150" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.mingName" 
        placeholder="请输入物资名称"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>

  <!-- 是否可回收列 -->
  <el-table-column label="是否可回收" width="120" align="center">
  <!-- 下拉框 -->
   <template #default="scope">
      <el-select v-model="scope.row.mingHui" placeholder="请选择" size="small">
        <el-option label="是" value="1" />
        <el-option label="否" value="0" />
      </el-select>
    </template>
  </el-table-column>
  
  <!-- 数量列 -->
  <el-table-column label="数量" width="100" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.mingShuliang" 
        placeholder="请输入数量"
        type="number"
        min="1"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>
  
  <!-- 物资名称列 -->

  
  <!-- 物资规格列 -->
  <el-table-column label="物资规格" width="150" align="center">
    <template #default="scope">
      <el-input 
        v-model="scope.row.mingGuige" 
        placeholder="请输入物资规格"
        size="small"
        class="compact-input"
      />
    </template>
  </el-table-column>



  <!-- 状态列 -->
  <el-table-column 
  prop="mingZhuangtai"
  :formatter="(row) => row.mingZhuangtai = row.mingZhuangtai || '1'"
  v-show="false"
></el-table-column>
</el-table>
         </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

   <!-- 查看出库详情 -->
   <el-dialog title="物资出库详情" v-model="viewOpen" width="700px" append-to-body>
  <el-descriptions :column="2" border>
    <el-descriptions-item label="出库单号">{{ viewForm.cDanhao }}</el-descriptions-item>
    <el-descriptions-item label="出库仓库">
      <span v-if="viewForm.kuId === viewForm.kuId">
        {{ viewForm.cangku?.kuName }}
      </span>
    </el-descriptions-item>
    <el-descriptions-item label="出库人">
      <span v-if="viewForm.yId === viewForm.yId">
        {{ viewForm.table12?.yName }}
      </span>
    </el-descriptions-item>

    <el-descriptions-item label="出库时间">{{ parseTime(viewForm.cShijian, '{y}-{m}-{d}') }}</el-descriptions-item>
    <el-descriptions-item label="领取人">{{ viewForm.cLingquren }}</el-descriptions-item>
  </el-descriptions>
  <div style="flex-grow: 1; overflow: hidden; display: flex; flex-direction: column; padding: 0 20px 20px;">
  <div style="font-weight: bold; margin: 10px 0 5px 0;">物资明细</div>
  <div style="flex-grow: 1; overflow: auto;">
    <el-table 
      :data="viewForm.mingxi ? [viewForm.mingxi] : []" 
      border 
      size="small"
      style="width: 100%;">
      <el-table-column prop="mingName" label="物资名称" width="120" fixed />
      <el-table-column prop="mingGuige" label="规格" width="120" />
      <el-table-column prop="wuziShangjia" label="供应商" width="130" />
      <el-table-column prop="mingShuliang" label="数量" width="130" align="center" />
      <el-table-column prop="mingHui" label="是否可回收" width="130" align="center">
        <template #default="scope">
          {{ scope.row.mingHui === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
    </el-table>
  </div>
  </div>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="viewOpen = false">关 闭</el-button>
    </div>
  </template>
</el-dialog>



<!-- 选择仓库明细的弹窗 -->
<el-dialog 
  title="物资信息" 
  v-model="warehouseDetailVisible" 
  width="80%"
  append-to-body>

  <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="mingxiAdd"
          v-hasPermi="['jiuzai:cangkumingxi:add']"
        >新增</el-button>
      </el-col>


  <el-table :data="wuzixinxiList" border style="width: 100%">
    <el-table-column label="序号" align="center" prop="wuziId" />
      <el-table-column label="物资编号" align="center" prop="wuziBianhao" />
      <el-table-column label="物资名称" align="center" prop="wuziName" />
      <el-table-column label="物资类别" align="center" prop="leibieId">
        <template v-slot="scope">
          <span v-if="scope.row.leibieId === scope.row.wuzileibie.leiId">
            {{ scope.row.wuzileibie.leiName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否为回收的物资" align="center" prop="wuziHui" />
      <el-table-column label="物资单位" align="center" prop="wuziDanwei" />
      <el-table-column label="物资数量" align="center" prop="wuziShu" />
      <el-table-column label="物资外部存储" align="center" prop="wuziWaibu" />
    <!-- 添加选择操作列 -->
    <el-table-column label="操作" width="120" align="center">
      <template #default="scope">
        <el-button 
          type="primary" 
          size="small" 
          @click="selectWarehouseItem(scope.row)">
          选择
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="warehouseDetailVisible = false">关闭</el-button>
    </div>
  </template>
</el-dialog>

  </div>
</template>

<script setup name="Chuku">
import { listChuku, getChuku, delChuku, addChuku, updateChuku } from "@/api/jiuzai/chuku"
import { listCangkumingxi, getCangkumingxi, delCangkumingxi, addCangkumingxi, updateCangkumingxi } from "@/api/jiuzai/cangkumingxi"
import { listCangku, getCangku, delCangku, addCangku, updateCangku } from "@/api/cangku/cangku"
import { listWuzi } from  "@/api/jiuzai/wuzi"
import { 
  listWuzixinxi, 
  getWuzixinxi, 
  updateWuzixinxi 
} from "@/api/jiuzai/wuzixinxi";

const { proxy } = getCurrentInstance()

const chukuList = ref([])
const open = ref(false)
const viewOpen = ref(false) // 新增查看对话框状态
const loading = ref(true)
const showSearch = ref(true)
const cangkuList = ref([])
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const viewForm = ref({}) // 新增查看表单数据
const wuziList  = ref([])
const total = ref(0)
const title = ref("")
const warehouseDetailVisible = ref(false) // 控制物资选择对话框的显示
const wuzixinxiList = ref([]) // 存储物资明细列表数据


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cDanhao: null,
    cChangku: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询物资出库列表 */
function getList() {
  loading.value = true
  listChuku(queryParams.value).then(response => {
    chukuList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}



function getCangkuList() {
  loading.value = true
  listCangku(queryParams.value).then(response => {
    cangkuList.value = response.rows
    // console.log(cangkuList.value)
    loading.value = false
  })
}
/** 查看按钮操作 */
function handleBatchView() {
  if (ids.value.length === 0) {
    proxy.$message.warning("请先选择要查看的记录");
    return;
  }
  if (ids.value.length > 1) {
    proxy.$message.warning("只能选择一条记录查看");
    return;
  }
  
  const cId  = ids.value[0];
  getChuku(cId).then(response => {
    viewForm.value = response.data;
    console.log(viewForm.value);
    viewOpen.value = true;
  });
}


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

function handleSelectMingxi() {
  loading.value = true
  warehouseDetailVisible.value = true 
  listWuzixinxi(queryParams.value).then(response => {
    wuzixinxiList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

function selectWarehouseItem(row) {
  if (!form.value.mingxiList) {
    form.value.mingxiList = []
  }
  
  // 将物资信息映射为明细格式
  const detailItem = {
    mingName: row.wuziName,  // 映射物资名称
    mingGuige: '',           // 初始化规格
    wuziShangjia: '',        // 初始化供应商
    mingDanjia: 0,           // 初始化单价
    mingShuliang: 1,         // 默认数量1
    wuziId: row.wuziId       // 保留物资ID
  }
  
  form.value.mingxiList.push(detailItem)
  warehouseDetailVisible.value = false
  proxy.$modal.msgSuccess("已选择物资明细")
}

function mingxiAdd() {
  zengjia()
  warehouseDetailAddVisible.value = true
  title.value = "添加物资出入库明细"
}


function zengjia() {
  form.value = {
    mingId: null,
    wuziId: null,
    rukuId: null,
    cId: null,
    wuziShangjia: null,
    mingRiqi: null,
    mingGuoriqi: null,
    mingMairiqi: null,
    mingDanjia: null,
    mingHui: null,
    mingShuliang: null,
    mingName: null,
    mingGuige: null,
    mingZhuangtai: null
  }
  proxy.resetForm("cangkumingxiRef")
}


// 表单重置
function reset() {
  form.value = {
    cId: null,
    kuId: null,
    yId: null,
    cDanhao: null,
    cChangku: null,
    cShijian: null,
    cLingquren: null,
    cZhuangtai: null,
    shenheDate: null,
    shenheUser: null,
    shenheBeizhu: null,
    shenheZhuangtai: null,
    mingxiList: [] // 添加这行
  }
  proxy.resetForm("chukuRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.cId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加物资出库"
  if (!form.value.cDanhao) {
    const now = new Date()
    const timePart = now.toISOString().replace(/[-:T.]/g, '').slice(2, 14)
    form.value.cDanhao = `CK${timePart}`
  }
}



/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _cId = row.cId || ids.value[0]; // 确保获取单个出库单ID
  
  // 1. 获取主表数据
  getChuku(_cId).then((response) => {
    form.value = {
      cId: response.data.cId,
      kuId: response.data.kuId,
      yId: response.data.yId,
      cDanhao: response.data.cDanhao,
      cShijian: response.data.cShijian,
      cLingquren: response.data.cLingquren,
      mingxiList: [] // 初始化为空数组
    };

    // 2. 直接调用 getCangkumingxi 按 cId 查询明细
    getCangkumingxi(_cId).then((detailRes) => {
  console.log("明细数据返回:", detailRes); // 检查返回的数据结构
  if (detailRes.data) {
    form.value.mingxiList = [{
      // 确保字段名匹配
      mingId: detailRes.data.mingId,
      wuziId: detailRes.data.wuziId,
      mingName: detailRes.data.mingName,
      mingGuige: detailRes.data.mingGuige,
      mingShuliang: detailRes.data.mingShuliang,
      mingHui: detailRes.data.mingHui
    }];
  }
}).catch((error) => {
      console.error("获取明细失败:", error);
      proxy.$modal.msgWarning("未找到关联的物资明细");
    });

    open.value = true;
    title.value = "修改物资出库";
  }).catch((error) => {
    console.error("获取主表数据失败:", error);
    proxy.$modal.msgError("加载数据失败，请检查控制台");
  });
}
/** 提交按钮 */

async function submitForm() {
  proxy.$refs["chukuRef"].validate(async (valid) => {
    if (valid) {
      try {
        // 1. 准备主表数据(排除明细)
        const mainFormData = { ...form.value };
        delete mainFormData.mingxiList;

        // 2. 提交主表并获取出库ID
        let res;
        if (form.value.cId) {
          res = await updateChuku(mainFormData);
        } else {
          res = await addChuku(mainFormData);
        }

        const cId = res?.data?.cId || form.value.cId;
        if (!cId) throw new Error("未获取到出库ID");

        // 3. 处理明细数据
        if (form.value.mingxiList?.length > 0) {
          await submitMingxiList(cId);
        }

         // 4. 更新物资信息表中的数量（出库模式，减少数量）
         await updateWuziQuantities(form.value.mingxiList, true);

        proxy.$modal.msgSuccess("操作成功");
        open.value = false;
        getList();
      } catch (error) {
        console.error("提交错误详情:", error);
        proxy.$modal.msgError(`操作失败: ${error.message}`);
      }
    }
  });
}


async function updateWuziQuantities(mingxiList, isOutbound = false) {
  try {
    for (const item of mingxiList) {
      const wuziRes = await getWuzixinxi(item.wuziId);
      const currentWuzi = wuziRes.data;
      
      let newQuantity = currentWuzi.wuziShu || 0;
      if (isOutbound) {
        // 出库 - 减少数量
        newQuantity -= Number(item.mingShuliang);
        if (newQuantity < 0) newQuantity = 0; // 防止负数
      } else {
        // 入库 - 增加数量
        newQuantity += Number(item.mingShuliang);
      }
      
      await updateWuzixinxi({
        ...currentWuzi,
        wuziShu: newQuantity
      });
    }
    proxy.$modal.msgSuccess("物资数量已更新");
  } catch (error) {
    console.error("更新物资数量失败:", error);
    throw error;
  }
}

async function submitMingxiList(cId) {
  try {
    if (!form.value.mingxiList?.length) return;

    const promises = form.value.mingxiList.map((item) => {
      return addCangkumingxi({
        ...item,
        cId: Number(cId), // 关联出库ID
      });
    });

    await Promise.all(promises);
    proxy.$modal.msgSuccess("物资明细提交成功");
  } catch (error) {
    console.error("明细提交失败:", error);
    throw error;
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _cIds = row.cId || ids.value;
  proxy.$modal.confirm('是否确认删除物资出库编号为"' + _cIds + '"的数据项？').then(function () {
    return delChuku(_cIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

function getjueseList() {
  loading.value = true
  listWuzi(queryParams.value).then(response => {
    wuziList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

onMounted(() => {
  getCangkuList();
  getjueseList()
});

/** 导出按钮操作 */
function handleExport() {
  proxy.download('jiuzai/chuku/export', {
    ...queryParams.value
  }, `chuku_${new Date().getTime()}.xlsx`)
}


getList()
</script>
